//
//  PAHeadImageView.m
//  PAMobileWallet
//
//  Created by Gavin Zhang on 7/14/13.
//  Copyright (c) 2013 平安付. All rights reserved.
//

#import "PAAsynImageView.h"
#import "PAImageRequest.h"
#import <QuartzCore/QuartzCore.h>
@interface  PAAsynImageView()
@property(nonatomic, strong)PAImageRequest *request;
@end


@implementation PAAsynImageView

@synthesize defaultImg          = _defaultImg;
@synthesize imgUrl              = _imgUrl;
@synthesize request             = _request;
@synthesize cornerRadius        = _cornerRadius;
@synthesize fadeAnimated        = _fadeAnimated;
@synthesize imgKey              = _imgKey;
@synthesize imgDigest           = _imgDigest;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        self.contentMode = UIViewContentModeScaleToFill;
        self.defaultImgName = @"home_photo.png";
    }
    return self;
}
- (void)setCornerRadius:(float)cornerRadius
{
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = cornerRadius;
}
- (void)setImgUrl:(NSString *)imgUrl key:(NSString *)key digest:(NSString *)digest
{
    /*
     * 应该有 比较是否需要更新的机制
     */
    _imgUrl = [imgUrl copy];
    
    self.layer.cornerRadius = self.cornerRadius;
    self.layer.masksToBounds = YES;
    self.image = self.defaultImg;
    self.imgKey = key;
    self.imgDigest = digest;
    if (_imgUrl) {
        [self loadImageFromUrl];
    }
}
- (void)setDefaultImgName:(NSString *)defaultImgName
{
    self.image = [UIImage imageNamed:defaultImgName];
}
- (void)stopUpdate
{
    [self.request cancel];
}
- (void)loadImageFromUrl
{
    [self.request clearDelegatesAndCancel];
    self.request = [[PAImageRequest alloc] initWithURL:[NSURL URLWithString:self.imgUrl]];
    self.request.key = self.imgKey;
    self.request.digest = self.imgDigest;
    self.request.paImageAsynDelegate = self;
    [[PAImageAsynManager sharedInstance] loadImgWithRequest:self.request];
}

#pragma mark - PAImageAsynDelegate
- (void)paImageRequestStarted
{
    /*
     * 可能有播放 等待动画类似的需求
     */
}

- (void)paImageRequestSuccess:(NSData *)data
{
    self.image = [UIImage imageWithData:data];
}
- (void)paImageRequestFailed
{
}
@end
